package com.king.wx;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.Files;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.king.wx.model.*;
import com.king.wx.param.BaseRequest;
import com.king.wx.param.UploadMediaRequest;
import com.king.wx.param.WxContext;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;

import java.io.File;
import java.io.IOException;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author TaoBangren
 * @version 1.0
 * @since 16/5/27 下午1:52
 */
public final class WxEngineer {

    private static final String APP_ID = "wx782c26e4c19acffb";

    private static final String BASE_URL = "https://login.weixin.qq.com";

    private static final String UUID_URL = BASE_URL + "/jslogin";

    private static final String QR_CODE_URL = BASE_URL + "/qrcode/";

    private static final String LOGIN_URL = BASE_URL + "/cgi-bin/mmwebwx-bin/login";

    private final WxContext wxContext;

    private AtomicInteger mediaCount = new AtomicInteger(0);

    public WxEngineer() {
        wxContext = new WxContext();
    }

    /**
     * 获取登录二维码
     * @return
     */
    public byte[] openQrCode() throws IOException {

        System.setProperty("jsse.enableSNIExtension", "false");

        String uuidUrl = UUID_URL + "?appid="+APP_ID+"&fun=new";
        String uuidRegx = "window.QRLogin.code = (\\d+); window.QRLogin.uuid = \"(\\S+?)\";";

        String response = wxContext.HTTP_CLIENT.get(uuidUrl);

        Pattern r = Pattern.compile(uuidRegx);

        Matcher m = r.matcher(response);

        if (m.find()) {
            wxContext.setUuid(m.group(2));
        } else {
            System.out.println("NO MATCH");
        }

        String qrCodeUrl = QR_CODE_URL + wxContext.getUuid();
        Files.write(wxContext.HTTP_CLIENT.getFile(qrCodeUrl), new File("/Users/TaoBangren/git@osc/king-training/wx-enginer/src/main/resources/qrCode.jpg"));
        return null;
    }

    private boolean checkLogin() throws Exception {
        String loginUrl = LOGIN_URL + "?tip=1&uuid="+wxContext.getUuid()+"&_="+System.currentTimeMillis();
        String codeRegx = "window.code=(\\d+);\\nwindow.redirect_uri=\"(\\S+)\";";
        Pattern r = Pattern.compile(codeRegx);

        while (true) {
            String response = wxContext.HTTP_CLIENT.get(loginUrl);
            Matcher m = r.matcher(response);
            if (m.find()) {
                String code = m.group(1);
                String redirectUri = m.group(2);
                if (code.equals("200")) {
                    response = wxContext.HTTP_CLIENT.get(redirectUri);

                    Document doc = DocumentHelper.parseText(response);
                    String skey = doc.selectSingleNode("/error/skey").getText();
                    String wxsid = doc.selectSingleNode("/error/wxsid").getText();
                    long wxuin = Long.valueOf(doc.selectSingleNode("/error/wxuin").getText());
                    String passTicket = doc.selectSingleNode("/error/pass_ticket").getText();

                    wxContext.setWxsid(wxsid);
                    wxContext.setWxuin(wxuin);
                    wxContext.setPassTicket(passTicket);
                    wxContext.setSkey(skey);
                    wxContext.setUrl(redirectUri.substring(0, redirectUri.lastIndexOf("/")));

                    return true;
                }
            }
        }
    }

    private boolean loginInit() {
        String initUrl = wxContext.getUrl() + "/webwxinit?r=" + System.currentTimeMillis();

        Map<String, BaseRequest> payloads = Maps.newHashMap();
        payloads.put("BaseRequest", wxContext.getBaseRequest());

        String response = wxContext.HTTP_CLIENT.post(initUrl, GsonUtils.toJson(payloads));

        JsonObject loginInit = GsonUtils.jsonToJsonObject(response);

        JsonObject userObj = loginInit.getAsJsonObject("User");
        Member currentMember = GsonUtils.fromJson(userObj.toString(), Member.class);

        JsonObject syncKeyObj = loginInit.getAsJsonObject("SyncKey");
        JsonArray syncKeyArr = syncKeyObj.getAsJsonArray("List");

        List<SyncKey> syncKeys = Lists.newArrayList();
        List<String> syncKeyStrs = Lists.newArrayList();
        for (int i = 0; i < syncKeyArr.size(); i++) {
            JsonObject obj = syncKeyArr.get(i).getAsJsonObject();
            syncKeys.add(new SyncKey(obj.get("Key").getAsString(), obj.get("Val").getAsString()));
            syncKeyStrs.add(obj.get("Key").getAsString() + "_" + obj.get("Val").getAsString());
        }
        wxContext.setSyncKeys(syncKeys);
        wxContext.setSyncKey(Joiner.on("%7C").join(syncKeyStrs.iterator()));

        wxContext.setWxuin(currentMember.getUin());
        wxContext.setCurrentMember(currentMember);
        return false;
    }

    private boolean wxStatusNotify() {
        String nofifyUrl = wxContext.getUrl() + "/webwxstatusnotify?lang=zh_CN&pass_ticket=" + wxContext.getPassTicket();
        Map<String, Object> payloads = Maps.newHashMap();
        payloads.put("BaseRequest", wxContext.getBaseRequest());
        payloads.put("Code", 3);
        payloads.put("FromUserName", wxContext.getCurrentMember().getUserName());
        payloads.put("ToUserName", wxContext.getCurrentMember().getUserName());
        payloads.put("ClientMsgId", System.currentTimeMillis());

        String response = wxContext.HTTP_CLIENT.post(nofifyUrl, GsonUtils.toJson(payloads));

        System.out.println(response);
        return false;
    }

    private List<Member> getBatchContact(String userName, String encryChatRoomId) {
        String batchContractUrl = wxContext.getUrl() + "/webwxbatchgetcontact?type=ex&r=" + System.currentTimeMillis() + "&pass_ticket=" + wxContext.getPassTicket();

        Map<String, Object> payloads = Maps.newHashMap();
        payloads.put("BaseRequest", wxContext.getBaseRequest());
        payloads.put("Count", 1);

        Map<String, Object> item = Maps.newHashMap();
        item.put("UserName", userName);
        item.put("EncryChatRoomId", encryChatRoomId);

        List<Map<String, Object>> lists = Lists.newArrayList();
        lists.add(item);

        payloads.put("List", lists);

        String response = wxContext.HTTP_CLIENT.post(batchContractUrl, GsonUtils.toJson(payloads));
        JsonObject batchContactObj = GsonUtils.jsonToJsonObject(response);
        JsonArray jsonArray = batchContactObj.getAsJsonArray("ContactList");

        JsonObject jsonObject = jsonArray.get(0).getAsJsonObject();
        Member member = GsonUtils.fromJson(jsonObject.toString(), Member.class);

        return member.getMemberList();
    }

    private boolean getContact() throws IOException {
        String contractUrl = wxContext.getUrl() + "/webwxgetcontact?r="+System.currentTimeMillis()+"&seq=0&skey="+wxContext.getSkey();

        String response = wxContext.HTTP_CLIENT.get(contractUrl);

        JsonObject batchContactObj = GsonUtils.jsonToJsonObject(response);
        JsonArray jsonArray = batchContactObj.getAsJsonArray("MemberList");

        initContact(jsonArray);
        return false;
    }

    private boolean initContact(JsonArray jsonArray) throws IOException {
        for (int i = 0; i < jsonArray.size(); i++) {
            JsonObject jsonObject = jsonArray.get(i).getAsJsonObject();
            Member member = GsonUtils.fromJson(jsonObject.toString(), Member.class);
//            getIconOrHeadImg(member);
            if (member.getUserName().startsWith("@@")) {
                if (wxContext.getChatRooms() == null) {
                    wxContext.setChatRooms(Lists.<Member>newArrayList());
                }

                if (wxContext.getChatRoomMap() == null) {
                    wxContext.setChatRoomMap(Maps.<String, Member>newHashMap());
                }

                if (!wxContext.getChatRoomMap().containsKey(member.getNickName())) {

                    List<Member> memberList = getBatchContact(member.getUserName(), "");
                    member.setMemberList(memberList);
                    member.setMemberCount(memberList.size());

                    wxContext.getChatRooms().add(member);
                    wxContext.getChatRoomMap().put(member.getNickName(), member);
                }
            } else if (member.getUserName().startsWith("@")) {
                if (wxContext.getContacts() == null) {
                    wxContext.setContacts(Lists.<Member>newArrayList());
                }

                if (wxContext.getContactMap() == null) {
                    wxContext.setContactMap(Maps.<String, Member>newHashMap());
                }

                if (!wxContext.getContactMap().containsKey(member.getNickName())) {
                    wxContext.getContacts().add(member);
                    wxContext.getContactMap().put(member.getNickName(), member);
                }
            }
        }
        return false;
    }

    private void startReceiving() throws Exception {
        while (true) {
            SyncCheck syncCheck = syncCheck();
            if (1100 == syncCheck.getRetcode()) {
                System.out.println("你在手机上登出了微信，债见");
                break;
            } else if (1101 == syncCheck.getRetcode()) {
                System.out.println("你在其他地方登录了 WEB 版微信，债见");
                break;
            } else if (0 == syncCheck.getRetcode()) {
                if (2 == syncCheck.getSelector()) {
                    produceMsg(getMsg());
                } else if (6 == syncCheck.getSelector()) {
                    // 收到疑似红包消息
                } else if (7 == syncCheck.getSelector()) {
                    // 你在手机上玩微信被我发现了
                    produceMsg(getMsg());
                }
            }
        }
    }

    private SyncCheck syncCheck() {
        String syncCheckUrl = wxContext.getUrl() + "/synccheck?r=" + System.currentTimeMillis() + "&skey=" + wxContext.getSkey() + "&sid=" + wxContext.getWxsid() +
                "&uin=" + wxContext.getWxuin() + "&deviceid=" + wxContext.getPassTicket() + "&synckey=" + wxContext.getSyncKey();

        String response = wxContext.HTTP_CLIENT.get(syncCheckUrl);

        String codeRegx = "retcode:\"(\\d+)\",selector:\"(\\d+)\"";
        Pattern r = Pattern.compile(codeRegx);
        Matcher m = r.matcher(response);

        if (m.find()) {
            return new SyncCheck(Integer.parseInt(m.group(1)), Integer.parseInt(m.group(2)));
        }

        return new SyncCheck(-1, -1);
    }

    private List<AddMsg> getMsg() {

        String getMsgUrl = wxContext.getUrl() + "/webwxsync?sid=" + wxContext.getWxsid()+ "&skey=" + wxContext.getSkey() + "&pass_ticket=" + wxContext.getPassTicket();

        Map<String, Object> payloads = Maps.newHashMap();
        payloads.put("BaseRequest", wxContext.getBaseRequest());

        Map<String, Object> syncKeyMap = Maps.newHashMap();
        syncKeyMap.put("Count", wxContext.getSyncKeys().size());
        syncKeyMap.put("List", wxContext.getSyncKeys());

        payloads.put("SyncKey", syncKeyMap);
        payloads.put("rr", System.currentTimeMillis());

        String response = wxContext.HTTP_CLIENT.post(getMsgUrl, GsonUtils.toJson(payloads));

        JsonObject resObj = GsonUtils.jsonToJsonObject(response);

        JsonObject syncKeyObj = resObj.getAsJsonObject("SyncKey");
        JsonArray syncKeyArr = syncKeyObj.getAsJsonArray("List");

        List<SyncKey> syncKeys = Lists.newArrayList();
        List<String> syncKeyStrs = Lists.newArrayList();
        for (int i = 0; i < syncKeyArr.size(); i++) {
            JsonObject obj = syncKeyArr.get(i).getAsJsonObject();
            syncKeys.add(new SyncKey(obj.get("Key").getAsString(), obj.get("Val").getAsString()));
            syncKeyStrs.add(obj.get("Key").getAsString() + "_" + obj.get("Val").getAsString());
        }
        wxContext.setSyncKeys(syncKeys);
        wxContext.setSyncKey(Joiner.on("%7C").join(syncKeyStrs.iterator()));

        List<AddMsg> addMsgList = Lists.newArrayList();
        int addMsgCount = resObj.getAsJsonPrimitive("AddMsgCount").getAsInt();
        if (addMsgCount > 0) {
            JsonArray addMsgArray = resObj.getAsJsonArray("AddMsgList");
            for (int i = 0; i< addMsgCount; i++) {
                JsonObject addMsgObj = addMsgArray.get(i).getAsJsonObject();
                AddMsg addMsg = GsonUtils.fromJson(addMsgObj.toString(), AddMsg.class);
                addMsg.setContent(addMsg.getContent().replaceAll("&lt;", "<").replaceAll("&gt;", ">"));
                addMsgList.add(addMsg);
            }
        }

        return addMsgList;
    }

    private boolean produceMsg(List<AddMsg> addMsgList) throws IOException {

        for (AddMsg addMsg : addMsgList) {
            if (addMsg.getFromUserName().startsWith("@@")) {
                produceGroupMsg(addMsg);
                continue;
            }

            if (addMsg.getMsgType() == 1) {
                // 文本
                System.out.println(addMsg.getContent());
                sendMsg(wxContext.getCurrentMember().getUserName(), addMsg.getFromUserName(), addMsg.getContent());
            } else if (addMsg.getMsgType() == 3) {
                // 图片
                String path = downloadImg(addMsg);
                sendImgMsg(wxContext.getCurrentMember().getUserName(), addMsg.getFromUserName(), path);
            } else if (addMsg.getMsgType() == 34) {
                // 语音
                String path = downloadVoice(addMsg);
                sendFileMsg(wxContext.getCurrentMember().getUserName(), addMsg.getFromUserName(), path);
            } else if (addMsg.getMsgType() == 37) {
                // 好友校验信息
                addFriendApply(addMsg);
            } else if (addMsg.getMsgType() == 42) {
                // 共享名片
            } else if (addMsg.getMsgType() == 43) {
                // 视频通话消息
                String path = downloadVideo(addMsg);
                sendFileMsg(wxContext.getCurrentMember().getUserName(), addMsg.getFromUserName(), path);
            } else if (addMsg.getMsgType() == 47) {
                // 动画表情(支持部分表情)
                String path = downloadImg(addMsg);
                sendImgMsg(wxContext.getCurrentMember().getUserName(), addMsg.getFromUserName(), path);
            } else if (addMsg.getMsgType() == 48) {
                // 位置信息
                System.out.println(wxContext.getUrl() + "/webwxgetmsgimg?MsgID=" + addMsg.getNewMsgId() + "&skey=" + wxContext.getSkey());
            } else if (addMsg.getMsgType() == 49) {
                // 分享链接
                if (addMsg.getAppMsgType() == 6) {
                    String path = downloadAtta(addMsg);
                    sendFileMsg(wxContext.getCurrentMember().getUserName(), addMsg.getFromUserName(), path);
                }
            } else if (addMsg.getMsgType() == 51) {
                // 微信初始化信息
            } else if (addMsg.getMsgType() == 62) {
                // 小视频
                String path = downloadVideo(addMsg);
                sendFileMsg(wxContext.getCurrentMember().getUserName(), addMsg.getFromUserName(), path);
            } else if (addMsg.getMsgType() == 10002) {
                // 撤回消息
            } else {
                // 可能是表情，图片, 链接或红包
            }
        }

        return false;
    }

    private boolean sendMsg(String fromUserName, String toUserName, String content) {
        String sendMsgUrl = wxContext.getUrl() + "/webwxsendmsg";
        Map<String, Object> payloads = Maps.newHashMap();
        payloads.put("BaseRequest", wxContext.getBaseRequest());

        SendMsg sendMsg = new SendMsg();
        sendMsg.setFromUserName(fromUserName);
        sendMsg.setToUserName(toUserName);
        sendMsg.setContent(content);
        sendMsg.setType(1);

        payloads.put("Msg", sendMsg);

        String response = wxContext.HTTP_CLIENT.post(sendMsgUrl, GsonUtils.toJson(payloads));
        SendMsgResponse sendMsgResponse = GsonUtils.fromJson(response, SendMsgResponse.class);

        return sendMsgResponse.getBaseResponse().getRet() == 0;
    }

    private boolean sendImgMsg(String fromUserName, String toUserName, String path) {
        String mediaId = uploadFile(path);
        String url = wxContext.getUrl() + "/webwxsendmsgimg?fun=async&f=json";

        Map<String, Object> payloads = Maps.newHashMap();
        payloads.put("BaseRequest", wxContext.getBaseRequest());

        SendImgMsg sendMsg = new SendImgMsg();

        sendMsg.setMediaId(mediaId);
        sendMsg.setFromUserName(fromUserName);
        sendMsg.setToUserName(toUserName);
        sendMsg.setLocalID(System.currentTimeMillis());
        sendMsg.setClientMsgId(System.currentTimeMillis());
        sendMsg.setType(3);

        if (path.endsWith(".gif")) {
            url = wxContext.getUrl() + "/webwxsendemoticon?fun=sys";
            sendMsg.setType(47);
            sendMsg.setEmojiFlag(2);
        }

        payloads.put("Msg", sendMsg);

        String response = wxContext.HTTP_CLIENT.post(url, GsonUtils.toJson(payloads));
        SendMsgResponse sendMsgResponse = GsonUtils.fromJson(response, SendMsgResponse.class);

        return sendMsgResponse.getBaseResponse().getRet() == 0;

    }

    private boolean sendFileMsg(String fromUserName, String toUserName, String path) {
        File file = new File(path);
        String mediaId = uploadFile(path);
        String url = wxContext.getUrl() + "/webwxsendappmsg?fun=async&f=json";

        Map<String, Object> payloads = Maps.newHashMap();
        payloads.put("BaseRequest", wxContext.getBaseRequest());

        SendMsg sendMsg = new SendMsg();
        sendMsg.setContent("<appmsg appid='wxeb7ec651dd0aefa9' sdkver=''><title>" + file.getName() + "</title>" +
                "<des></des><action></action><type>6</type><content></content><url></url><lowurl></lowurl>" +
                "<appattach><totallen>" + file.length() + "</totallen><attachid>"+mediaId+"</attachid>" +
                "<fileext>"+file.getName().substring(file.getName().lastIndexOf(".") + 1)+"</fileext></appattach><extinfo></extinfo></appmsg>");
        sendMsg.setFromUserName(fromUserName);
        sendMsg.setToUserName(toUserName);
        sendMsg.setLocalID(System.currentTimeMillis());
        sendMsg.setClientMsgId(System.currentTimeMillis());
        sendMsg.setType(6);

        payloads.put("Msg", sendMsg);

        String response = wxContext.HTTP_CLIENT.post(url, GsonUtils.toJson(payloads));
        SendMsgResponse sendMsgResponse = GsonUtils.fromJson(response, SendMsgResponse.class);

        return sendMsgResponse.getBaseResponse().getRet() == 0;

    }

    private String downloadImg(AddMsg addMsg) throws IOException {
        String url = wxContext.getUrl() + "/webwxgetmsgimg?MsgID=" + addMsg.getNewMsgId() + "&skey=" + wxContext.getSkey();

        String ext = ".jpg";
        if (addMsg.getMsgType() == 47) {
            ext = ".gif";
        }

        String filePath = "/Users/TaoBangren/git@osc/king-training/wx-enginer/src/main/resources/" + System.currentTimeMillis() + ext;
        byte[] imgBytes = wxContext.HTTP_CLIENT.getFile(url);
        Files.write(imgBytes, new File(filePath));

        return filePath;
    }

    private String downloadVideo(AddMsg addMsg) throws IOException {
        String url = wxContext.getUrl() + "/webwxgetvideo?fun=download&msgid=" + addMsg.getNewMsgId() + "&skey=" + wxContext.getSkey();
        byte[] voiceBytes = null;

        while (voiceBytes == null || voiceBytes.length <= 0) {
            voiceBytes = wxContext.HTTP_CLIENT.getFile(url);
        }

        String filePath = "/Users/TaoBangren/git@osc/king-training/wx-enginer/src/main/resources/" + System.currentTimeMillis() + ".mp4";
        Files.write(voiceBytes, new File(filePath));
        return filePath;
    }

    private String downloadVoice(AddMsg addMsg) throws IOException {
        String url = wxContext.getUrl() + "/webwxgetvoice?msgid=" + addMsg.getNewMsgId() + "&skey=" + wxContext.getSkey();
        byte[] voiceBytes = wxContext.HTTP_CLIENT.getFile(url);
        String filePath = "/Users/TaoBangren/git@osc/king-training/wx-enginer/src/main/resources/" + System.currentTimeMillis() + ".mp3";
        Files.write(voiceBytes, new File(filePath));
        return filePath;
    }

    private String downloadAtta(AddMsg addMsg) throws IOException {
        String url = "https://file.wx.qq.com/cgi-bin/mmwebwx-bin/webwxgetmedia?f=json";
        if (wxContext.getUrl().contains("2")) {
            url = "https://file2.wx.qq.com/cgi-bin/mmwebwx-bin/webwxgetmedia?f=json";
        }

        url = url + "&sender=" + addMsg.getFromUserName() + "&mediaid=" + addMsg.getMediaId() + "&filename=" + addMsg.getFileName() +
                "&fromuser=" + wxContext.getWxuin() + "&pass_ticket=undefined" + "&webwx_data_ticket=" + wxContext.HTTP_CLIENT.getCookieVal("webwx_data_ticket");

        byte[] attaBytes = wxContext.HTTP_CLIENT.getFile(url);
        String filePath = "/Users/TaoBangren/git@osc/king-training/wx-enginer/src/main/resources/" + addMsg.getFileName();

        Files.write(attaBytes, new File(filePath));
        return filePath;
    }

    private String uploadFile(String filePath) {

        String url = "https://file.wx.qq.com/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json";
        if (wxContext.getUrl().contains("2")) {
            url = "https://file2.wx.qq.com/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json";
        }

        File file = new File(filePath);
        String fileName = file.getName();
        String mimeType= URLConnection.guessContentTypeFromName(file.getName());
        if (Strings.isNullOrEmpty(mimeType)) {
            mimeType = "application/octet-stream";
        }
        String mediaType = mimeType.split("/")[0].equals("image") ? "pic" : "doc";

        String lastModifieDate = "Thu Mar 17 2016 00:55:10 GMT+0800 (CST)";
        String id = "WU_FILE_" + mediaCount.getAndIncrement();
        long fileSize = file.length();
        String webwxDataTicket = wxContext.HTTP_CLIENT.getCookieVal("webwx_data_ticket");

        UploadMediaRequest uploadMediaRequest = new UploadMediaRequest();
        uploadMediaRequest.setBaseRequest(wxContext.getBaseRequest());
        uploadMediaRequest.setClientMediaId(System.currentTimeMillis());
        uploadMediaRequest.setDataLen(fileSize);
        uploadMediaRequest.setMediaType(4);
        uploadMediaRequest.setStartPos(0);
        uploadMediaRequest.setTotalLen(fileSize);

        Map<String, String> params = Maps.newHashMap();
        params.put("id", id);
        params.put("name", fileName);
        params.put("type", mimeType);
        params.put("lastModifieDate", lastModifieDate);
        params.put("size", String.valueOf(fileSize));
        params.put("mediatype", mediaType);
        params.put("uploadmediarequest", GsonUtils.toJson(uploadMediaRequest));
        params.put("webwx_data_ticket", webwxDataTicket);
        params.put("pass_ticket", wxContext.getPassTicket());

        String response = wxContext.HTTP_CLIENT.postFile(url, filePath, params);

        UploadMediaResponse uploadMediaResponse = GsonUtils.fromJson(response, UploadMediaResponse.class);
        return uploadMediaResponse.getMediaId();
    }

    private void produceGroupMsg(AddMsg addMsg) {
        System.out.println("来自群消息===>" + addMsg.getContent());
    }

    public void sendVerifyUser(String verifyContent, List<Member> memberList) {
        String url = wxContext.getUrl() + "/webwxverifyuser?r=" + System.currentTimeMillis() + "&pass_ticket=" + wxContext.getPassTicket();

        Map<String, Object> payloads = Maps.newHashMap();
        payloads.put("BaseRequest", wxContext.getBaseRequest());
        payloads.put("Opcode", 2);
        payloads.put("VerifyUserListSize", memberList.size());

        List<Map<String, Object>> verifyUserList = Lists.newArrayList();
        for (Member member : memberList) {
            Map<String, Object> verifyUser = Maps.newHashMap();
            verifyUser.put("Value", member.getUserName());
            verifyUser.put("VerifyUserTicket", "");
            verifyUserList.add(verifyUser);
        }
        payloads.put("VerifyUserList", verifyUserList);
        payloads.put("VerifyContent", verifyContent);
        payloads.put("SceneListCount", 1);
        List<Integer> sceneList = Lists.newArrayList();
        sceneList.add(33);
        payloads.put("SceneList", sceneList);
        payloads.put("skey", wxContext.getSkey());

        String response = wxContext.HTTP_CLIENT.post(url, GsonUtils.toJson(payloads));
        System.out.println(response);
    }

    private void addFriendApply(AddMsg addMsg) {
        String url = wxContext.getUrl() + "/webwxverifyuser?r=" + System.currentTimeMillis() + "&pass_ticket=" + wxContext.getPassTicket();

        Map<String, Object> payloads = Maps.newHashMap();
        payloads.put("BaseRequest", wxContext.getBaseRequest());
        payloads.put("Opcode", addMsg.getStatus());
        payloads.put("VerifyUserListSize", 1);

        List<Map<String, Object>> verifyUserList = Lists.newArrayList();
        Map<String, Object> verifyUser = Maps.newHashMap();
        verifyUser.put("Value", addMsg.getRecommendInfo().getUserName());
        verifyUser.put("VerifyUserTicket", addMsg.getTicket());
        verifyUserList.add(verifyUser);
        payloads.put("VerifyUserList", verifyUserList);
        payloads.put("VerifyContent", "");
        payloads.put("SceneListCount", 1);
        List<Integer> sceneList = Lists.newArrayList();
        sceneList.add(33);
        payloads.put("SceneList", sceneList);
        payloads.put("skey", wxContext.getSkey());

        String response = wxContext.HTTP_CLIENT.post(url, GsonUtils.toJson(payloads));
        System.out.println(response);
    }

    private boolean createChatRoom(String topic, List<Member> memberList) {
        String url = wxContext.getUrl() + "/webwxcreatechatroom?pass_ticket="+wxContext.getPassTicket()+"&r=" + System.currentTimeMillis();
        Map<String, Object> payloads = Maps.newHashMap();
        payloads.put("BaseRequest", wxContext.getBaseRequest());
        payloads.put("MemberCount", memberList.size());
        List<Map<String, String>> userNameList = Lists.newArrayList();
        for (Member member : memberList) {
            Map<String, String> userName = Maps.newHashMap();
            userName.put("UserName", member.getUserName());
            userNameList.add(userName);
        }
        payloads.put("MemberList", userNameList);
        payloads.put("Topic", topic);

        String response = wxContext.HTTP_CLIENT.post(url, GsonUtils.toJson(payloads));
        System.out.println(response);

        return true;
    }

    private boolean removeMemberFromChatRoom(String chatRoomName, List<Member> memberList) {
        String url = wxContext.getUrl() + "/webwxupdatechatroom?fun=delmember&pass_ticket=" + wxContext.getPassTicket();
        Map<String, Object> payloads = Maps.newHashMap();
        payloads.put("BaseRequest", wxContext.getBaseRequest());
        payloads.put("ChatRoomName", chatRoomName);
        List<String> userNameList = Lists.newArrayList();
        for (Member member : memberList) {
            userNameList.add(member.getUserName());
        }
        String delMemberList = Joiner.on(",").join(userNameList.iterator());
        payloads.put("DelMemberList", delMemberList);

        String response = wxContext.HTTP_CLIENT.post(url, GsonUtils.toJson(payloads));
        System.out.println(response);

        return true;
    }

    private boolean addMemberIntoChatRoom(String chatRoomName, List<Member> memberList) {
        String url = wxContext.getUrl() + "/webwxupdatechatroom?fun=addmember&pass_ticket=" + wxContext.getPassTicket();
        Map<String, Object> payloads = Maps.newHashMap();
        payloads.put("BaseRequest", wxContext.getBaseRequest());
        payloads.put("ChatRoomName", chatRoomName);
        List<String> userNameList = Lists.newArrayList();
        for (Member member : memberList) {
            userNameList.add(member.getUserName());
        }
        String addMemberList = Joiner.on(",").join(userNameList.iterator());
        payloads.put("AddMemberList", addMemberList);

        String response = wxContext.HTTP_CLIENT.post(url, GsonUtils.toJson(payloads));
        System.out.println(response);

        return true;
    }

    private String getIconOrHeadImg(Member member) throws IOException {
        byte[] imgBytes = wxContext.HTTP_CLIENT.getFile("https://wx.qq.com/"+ member.getHeadImgUrl());
        String filePath = "/Users/TaoBangren/git@osc/king-training/wx-enginer/src/main/resources/" + member.getUserName() + ".jpg";

        Files.write(imgBytes, new File(filePath));
        return filePath;
    }

    public static void main (String [] args) throws Exception {
        WxEngineer wxEngineer = new WxEngineer();
        wxEngineer.openQrCode();
        wxEngineer.checkLogin();
        wxEngineer.loginInit();
        wxEngineer.wxStatusNotify();
        wxEngineer.getContact();
        System.out.println("======> wx init success!!!");
//        wxEngineer.startReceiving();

        List<Member> memberList = wxEngineer.wxContext.getChatRoomMap().get("聊聊架构1号群").getMemberList();
        int i = 0;
        for (Member member : memberList) {
            if (!wxEngineer.wxContext.getContactMap().containsKey(member.getNickName())) {
                wxEngineer.sendVerifyUser("技术架构交流,我是陶邦仁", Lists.newArrayList(member));
                System.out.println("======>发送第"+(i++)+"个添加好友邀请:" + member.getNickName());
                Thread.sleep(20000);
            }
        }
    }
}
